package Controller

import (
	"backend/Dao"
	"backend/Service/dbService"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"reflect"
	"strconv"
)

type DiscussController struct {
}

func StructConvertMap(obj interface{}, tagName string) map[string]interface{} {
	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)

	var data = make(map[string]interface{})
	for i := 0; i < t.NumField(); i++ {
		tagName := t.Field(i).Tag.Get(tagName)
		fmt.Println(tagName)
		if tagName != "" && tagName != "-" {
			data[tagName] = v.Field(i).Interface()
		}
	}
	return data
}

type reqAddNewDiscussTopic struct {
	Topic   string `json:"topic"`
	Content string `json:"content"`
}

//
// AddNewDiscussTopic
// @Description: 新增讨论话题
// @author MaTaoXun 2022-01-15 17:09:19
// @return gin.HandlerFunc
//
func (this DiscussController) AddNewDiscussTopic(c *gin.Context) {
	userId, _ := c.Get("userId")
	id, _ := strconv.Atoi(userId.(string))
	bodyData := reqAddNewDiscussTopic{}
	c.BindJSON(&bodyData)

	dbService.DbConn.Create(&Dao.TopicDiscussion{
		Model:       Dao.GetModel(),
		Content:     bodyData.Content,
		Topic:       bodyData.Topic,
		SponsorId:   id,
		IfDone:      0,
		IfTeacher:   1,
		IfImportant: 0,
		MsgCount:    0,
	})
}

//
// PageDiscussTopic
// @Description: 分页查询讨论话题
// @author MaTaoXun 2022-01-15 17:09:33
// @return gin.HandlerFunc
//
func (this DiscussController) PageDiscussTopic(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	page, _ := strconv.Atoi(c.Query("page"))
	var data []Dao.TopicDiscussion
	var count int64
	dbService.DbConn.Limit(pageSize).Offset((page - 1) * pageSize).Find(&data)
	dbService.DbConn.Model(&Dao.TopicDiscussion{}).Count(&count)
	c.JSON(200, &struct {
		Data  []Dao.TopicDiscussion
		Count int64
	}{
		data,
		count,
	})
}

type resListDiscussTopic struct {
	Dao.TopicDiscussion
	SponsorName string
}

// ListDiscussTopic
// @Summary 分页获取讨论话题
// @Description 分页获取讨论话题
// @Tags 讨论相关接口
// @Accept application/json
// @Produce application/json
// @Param tk header string false "token"
// @Param done query int false "是否已经结题"
// @Param onlyTeacher query int false "是否属于教师"
// @Param like query string false "模糊检索"
// @Param important query int false "是否重要"
// @Param pageSize query string false "分页大小"
// @Param page query string false "页码"
// @Success 200 body []resListDiscussTopic
// @Router /ListDiscussTopic [get]
func (this DiscussController) ListDiscussTopic(c *gin.Context) {
	done := c.Query("done")
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	page, _ := strconv.Atoi(c.Query("page"))
	onlyTeacher := c.Query("onlyTeacher")
	important := c.Query("important")
	like := c.Query("like")
	condition := make(map[string]interface{})
	atoi, _ := strconv.Atoi(done)
	condition["if_done"] = atoi
	if onlyTeacher == "1" {
		condition["if_teacher"] = 1
	}
	if important == "1" {
		condition["if_important"] = 1
	}

	var rs []resListDiscussTopic
	TopicDiscussionList := make([]struct {
		Dao.TopicDiscussion
		StuName     string
		TeacherName string
	}, 0)
	sel := dbService.DbConn.Model(&Dao.TopicDiscussion{}).
		Select("topic_discussion.*, student.stu_name, teacher.teacher_name").
		Where(condition).
		Joins("left join student on topic_discussion.sponsor_id = student.id").
		Joins("left join teacher on topic_discussion.sponsor_id = teacher.id").
		Order("topic_discussion.id DESC").
		Limit(pageSize).Offset((page - 1) * pageSize)
	if like != "" {
		sel = sel.Where("topic_discussion.topic LIKE ?", "%"+like+"%")
	}
	sel.Scan(&TopicDiscussionList)

	//dbService.DbConn.Raw("select a.*,tc.teacher_name,s.stu_name from topic_discussion a LEFT JOIN teacher tc on a.sponsor_id = tc.id left join student s on a.sponsor_id = s.id where ? ? a.if_done= ? order by a.id DESC ;", importantStr, teacherStr, done).Scan(&TopicDiscussionList)
	for _, item := range TopicDiscussionList {
		if item.IfTeacher == 1 {
			tpcDis := Dao.TopicDiscussion{}
			copier.Copy(&tpcDis, &item)
			rs = append(rs, resListDiscussTopic{TopicDiscussion: tpcDis, SponsorName: item.TeacherName})
		} else {
			tpcDis := Dao.TopicDiscussion{}
			copier.Copy(&tpcDis, &item)
			rs = append(rs, resListDiscussTopic{TopicDiscussion: tpcDis, SponsorName: item.StuName})
		}
	}
	c.JSON(200, rs)
}

//
// UpdateDiscussTopic
// @Description: 修改讨论话题
// @author MaTaoXun 2022-01-15 17:10:20
// @return gin.HandlerFunc
//
func (this DiscussController) UpdateDiscussTopic(c *gin.Context) {
	data := Dao.TopicDiscussion{}
	c.BindJSON(&data)
	convertMap := StructConvertMap(data, "map")
	fmt.Println(convertMap)
	updates := dbService.DbConn.Model(&Dao.TopicDiscussion{}).Where("id = ?", data.ID).Updates(convertMap)
	if updates.Error != nil {
		fmt.Println(updates.Error)
	}
	c.String(200, "ok")
}

//
// DelDiscussTopic
// @Description: 删除讨论话题
// @author MaTaoXun 2022-01-15 17:10:29
// @return gin.HandlerFunc
//
func (this DiscussController) DelDiscussTopic(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	dbService.DbConn.Where("id = ?", id).Delete(&Dao.TopicDiscussion{})
	var contents_discussions []Dao.ContentsDiscussion
	dbService.DbConn.Where("topic_id = ?", id).Find(&contents_discussions)
	dbService.DbConn.Where("topic_id = ?", id).Delete(&Dao.ContentsDiscussion{})
	for _, discussion := range contents_discussions {
		var rep_content_discussions Dao.RepContentDiscussion
		dbService.DbConn.Where("contents_discussion_id = ?", discussion.ID).Delete(&rep_content_discussions)
	}

	c.String(200, "ok")
}
